package com.sayimo.maker.mall.goods.service.impl;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.client.solrj.response.SpellCheckResponse;
import org.apache.solr.client.solrj.response.SpellCheckResponse.Suggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sayimo.framework.common.util.StringUtil;
import com.sayimo.framework.exception.DaoException;
import com.sayimo.framework.exception.ServiceException;
import com.sayimo.maker.activity.dao.BaseActivityDao;
import com.sayimo.maker.activity.dao.BaseCutDao;
import com.sayimo.maker.activity.dao.BaseGroupBuyDao;
import com.sayimo.maker.activity.dao.BaseMoldbabyDao;
import com.sayimo.maker.activity.dao.BaseSeckillDao;
import com.sayimo.maker.activity.dao.BaseSeckillGoodsDao;
import com.sayimo.maker.activity.dao.BaseSeckillTimesDao;
import com.sayimo.maker.activity.vo.BaseCut;
import com.sayimo.maker.base.dao.BasePhotoInterfaceDao;
import com.sayimo.maker.base.vo.BasePhoto;
import com.sayimo.maker.commons.Constant;
import com.sayimo.maker.commons.utils.HttpUtils;
import com.sayimo.maker.commons.utils.JSONUtil;
import com.sayimo.maker.commons.utils.PropertiesUtils;
import com.sayimo.maker.commons.utils.SearchUtil;
import com.sayimo.maker.commons.utils.SignUtil;
import com.sayimo.maker.mall.goods.dao.GoodsCollectionDao;
import com.sayimo.maker.mall.goods.dao.GoodsListInterfaceDao;
import com.sayimo.maker.mall.goods.dao.GoodsNormsValuesInterfaceDao;
import com.sayimo.maker.mall.goods.service.GoodsCommentIterfaceService;
import com.sayimo.maker.mall.goods.service.GoodsListInterfaceService;
import com.sayimo.maker.mall.goods.vo.GoodsCollection;
import com.sayimo.maker.mall.goods.vo.GoodsList;
import com.sayimo.maker.mall.orders.dao.OrdersListInterfaceDao;
import com.sayimo.maker.mall.orders.service.OrderPeriodInterfaceService;
import com.sayimo.maker.mall.search.vo.SearchField;



/**
 * @Project: schoolmallapi
 * @ClassName: GoodsListInterfaceImplService
 * @Description: 商品列表service
 * @Author: 曹频辉
 * @Date: 日期：2016年1月4日 时间：上午10:11:03
 * @Version 1.0.0
 */
@Service(value = "goodsListInterfaceImplService")
public class GoodsListInterfaceImplService implements GoodsListInterfaceService {

	private static Log logger = LogFactory.getLog(GoodsListInterfaceImplService.class);
	private static final String app_key = PropertiesUtils.getValue("TSH_APP_KEY");
	private static final String dist_code = PropertiesUtils.getValue("TSH_DIST_CODE");
	private static final Integer typeId = 1;
	private static final String token = PropertiesUtils.getValue("TSH_TOKEN");
	private static final String url = PropertiesUtils.getValue("TSH_URL");

	@Resource(name = "goodsListInterfaceImplDao")
	private GoodsListInterfaceDao goodsListInterfaceDao;
	@Autowired
	private OrderPeriodInterfaceService orderPeriodInterfaceService;
	@Autowired
	private GoodsCommentIterfaceService goodsCommentIterfaceService;// 商品评论Service
	@Autowired
	private BaseActivityDao baseActivityDao;
	@Autowired
	private BaseMoldbabyDao baseMoldbabyDao;
	@Autowired
	private GoodsNormsValuesInterfaceDao goodsNormsValuesInterfaceDao;// 商品规格值dao
	@Resource(name = "ordersListInterfaceDao")
	private OrdersListInterfaceDao ordersListInterfaceDao;
	@Resource(name="goodsCollectionDao")
	private GoodsCollectionDao goodsCollectionDao;
	@Autowired
	private BaseSeckillDao baseSeckillDao;
	@Autowired
	private BaseGroupBuyDao baseGroupBuyDao;
	@Autowired
	private BaseCutDao baseCutDao;
	@Autowired
	private BaseSeckillTimesDao baseSeckillTimesDao;
	@Autowired
	private BaseSeckillGoodsDao baseSeckillGoodsDao;
	@Resource(name="basePhotoDao")
	private BasePhotoInterfaceDao basePhotoDao;
	
	

	@Autowired
	private HttpServletRequest request;
	
	
	public GoodsNormsValuesInterfaceDao getGoodsNormsValuesInterfaceDao() {
		return goodsNormsValuesInterfaceDao;
	}

	public void setGoodsNormsValuesInterfaceDao(GoodsNormsValuesInterfaceDao goodsNormsValuesInterfaceDao) {
		this.goodsNormsValuesInterfaceDao = goodsNormsValuesInterfaceDao;
	}

	public GoodsCommentIterfaceService getGoodsCommentIterfaceService() {
		return goodsCommentIterfaceService;
	}

	public void setGoodsCommentIterfaceService(GoodsCommentIterfaceService goodsCommentIterfaceService) {
		this.goodsCommentIterfaceService = goodsCommentIterfaceService;
	}

	public OrderPeriodInterfaceService getOrderPeriodInterfaceService() {
		return orderPeriodInterfaceService;
	}

	public void setOrderPeriodInterfaceService(OrderPeriodInterfaceService orderPeriodInterfaceService) {
		this.orderPeriodInterfaceService = orderPeriodInterfaceService;
	}

	/**
	 * @Title: queryGoodsById
	 * @Description: 商品详情
	 * @param goodsId
	 * @param areaCode
	 * @param isActivity
	 * @param normsValueId
	 * @param customerId
	 * @throws ServiceException
	 * @return Map
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public Map updateQueryGoodsById(Integer normsValueId, Integer goodsId, Integer customerId, String areaCode,
			String isActivity, String identifier, Integer seckillTimesId) throws ServiceException {
		Map map = new HashMap();
		try {
			if(normsValueId==0){
				normsValueId=goodsListInterfaceDao.getNormsValueIdByGoodsId(goodsId);
				if(normsValueId==null){
					map.put(Constant.STATUS, Constant.STATUS_ERROR);
					map.put(Constant.ERROR_CODE, Constant.SELECT_ERROR);
					return map;
				}
			}
			Map goodsMap = goodsListInterfaceDao.getGoodsByGoodsId(goodsId);
			goodsMap.put("Tshstatus", 1);
			Map orderMap = new HashMap();
			List list = new ArrayList();
			if (isActivity != null && !isActivity.equals("") && isActivity.equals("1") && identifier != null
					&& !identifier.equals("") && identifier.contains("CYGHMZS")) {
				Map actMap = this.baseActivityDao.selectBaseActivityIdentifier(identifier);
				String goodsIds = (String) actMap.get("goodsIds");
				String ids[] = goodsIds.split(",");
				for (String id : ids) {
					List Olist = this.ordersListInterfaceDao.queryCustomerOrderList(customerId, Integer.parseInt(id),
							identifier);
					list.addAll(Olist);
				}
				if (!list.isEmpty()) {
					orderMap = (Map) list.get(0);
				}
				goodsMap.put("canBuyThis", "YES");

			} else if (isActivity != null && !isActivity.equals("") && isActivity.equals("1") && identifier != null
					&& !identifier.equals("") && identifier.contains("CYBK")) {
				List Olist = this.ordersListInterfaceDao.queryCustomerOrderList(customerId, goodsId, identifier);
				if (!Olist.isEmpty()) {
					orderMap = (Map) Olist.get(0);
				}

				if (Olist.isEmpty()) {
					goodsMap.put("canBuyThis", "YES");
				} else {
					goodsMap.put("canBuyThis", "NO");
				}
				if (!Olist.isEmpty() && ((Integer) orderMap.get("status") == 1)) {
					goodsMap.put("canBuyThis", "unPay");
				}

			}

			if (customerId != null) {
				boolean b = goodsCommentIterfaceService.canComment(customerId, goodsId);
				if (b) {
					goodsMap.put("canComment", "YES");
				} else {
					goodsMap.put("canComment", "NO");
				}
			} else {
				goodsMap.put("canComment", "");
			}

			if (goodsMap.get("goodsProduce") == null) {
				goodsMap.put("goodsProduce", "");
			}
			if (goodsMap.get("goodsAttr") == null) {
				goodsMap.put("goodsAttr", "");
			}
			if (goodsMap.get("sendAddress") == null) {
				goodsMap.put("sendAddress", "");
			}
			if (goodsMap.get("extraInfo") == null) {
				goodsMap.put("extraInfo", "");
			}
			if (goodsMap.get("isTurnBack") == null) {
				goodsMap.put("isTurnBack", "");
			}
			goodsMap.put("normsValueId", normsValueId);
			goodsMap.put("status", goodsMap.get("status"));
//			Map orderPeriodMap = orderPeriodInterfaceService.queryOrderPeriodInfoByGoodsId(goodsId);
//			if (orderPeriodMap != null && orderPeriodMap.get("status") != null
//					&& ((String) orderPeriodMap.get("status")).equals("0")) {
//				map.put(Constant.STATUS, Constant.STATUS_ERROR);
//				map.put(Constant.ERROR_CODE, Constant.SELECT_ERROR);
//				return map;
//			} else {
//				goodsMap.put("orderPeriod", orderPeriodMap);
//			}
			List photoList = goodsListInterfaceDao.getPhotosBygoodsId(goodsId);
			if (photoList != null && photoList.size() >= 0) {
				Map normList = goodsListInterfaceDao.getAllNormsByGoodsId(goodsId, normsValueId);
				if (normList != null) {

					String ids = (String) normList.get("normsValue");
					String[] strings = ids.split(",");
					StringBuffer stringBuffer = new StringBuffer();
					for (int j = 0; j < strings.length; j++) {
						if (!"0".equals(strings[j])) {
							String tempString = goodsNormsValuesInterfaceDao
									.getNormsValueById(Integer.valueOf(strings[j]));
							stringBuffer.append(tempString);
							if (j != (strings.length - 1)) {
								stringBuffer.append(" ");
							}

						}
					}
					normList.put("normsValue", stringBuffer.toString());

					// 获得特奢汇供应商编号
//					Integer providerId = (Integer) goodsListInterfaceDao.queryProviderByCode("TSH00").get("id");
//					GoodsList goodsList = goodsListInterfaceDao.queryProviderId(goodsId);
//					if (providerId == goodsList.getProviderId()) {
//
//						// 如果是特奢汇商品,则展示特奢汇的库存
//						Map<String, Object> paramMap = new HashMap<String, Object>();
//						paramMap.put("goodsId", goodsId);
//						paramMap.put("normsValueId", normsValueId);
//						Map<String, Object> tMap = goodsListInterfaceDao.querySkucodeById(paramMap);
//
//						String stockJson = getTshGoodStockNum((String) tMap.get("skuCode"));
//
//						logger.info("stockJson:" + stockJson);
//						Map<String, Object> jsonMap = JSONUtil.readValueToMap(stockJson);
//						if (!jsonMap.get("code").equals("02010250021")) {
//							List<Map<String, Object>> stockData = (List<Map<String, Object>>) JSONUtil
//									.readValueToMap(stockJson).get("data");
//
//							logger.info("stock:" + ((Double) stockData.get(0).get("stock")).intValue());
//
//							normList.put("stock", ((Double) stockData.get(0).get("stock")).intValue());
//						}
//						
//						// 获取特奢汇商品状态
//						// 请求“特奢汇”，查询商品状态
//		    			String statusJson = checkGoodStatus((String)tMap.get("skuCode"));
//		    			Map<String, Object> statusMap = JSONUtil.readValueToMap(statusJson);
//		    			String statusCode = statusMap.get("code").toString();
//		    			if(!statusCode.equals("0")){
//		    				//不是分销商品,将商品下架
//		    				goodsMap.put("Tshstatus", 2);
//		    				goodsMap.put("goodId", goodsId);
//		    				goodsMap.put("status", 2);
//		    				goodsListInterfaceDao.updateStatus(goodsMap);
//		    			}
//						
//					}
					
					if(isActivity != null && !isActivity.equals("") && isActivity.equals("1") ){
						//如果为秒抢活动
						if ( identifier != null	&& !identifier.equals("") && (identifier.contains("PT_SPMQ"))) {
							//获取秒抢活动信息
							Map<String,Object> actMap = this.baseSeckillDao.selectBaseSeckillIdentifier(identifier);
							//秒抢活动限购
							Integer goodsBuy = (Integer) actMap.get("goodsRestrictions");
							
							Integer customerGoodsBuy =0;
							//获取会员当天在该活动的当前时间段购买商品总数
							customerGoodsBuy = ordersListInterfaceDao.getCustomerSeckillGoodsBuy(customerId,identifier,seckillTimesId);
							
							//会员是否参与过活动，已购买过活动商品
							if(customerGoodsBuy==0){
								goodsMap.put("isBuy", "No");
							}else{
								goodsMap.put("isBuy", "YES");
							}
							
							//获取秒抢活动商品信息
							Map<String,Object> activityGoodsMap = this.baseSeckillGoodsDao.querySeckillGoodsInfoByGoodsId(goodsId,identifier,seckillTimesId);
							//如果活动价有%为按价格打折，否则为活动价格
							if(activityGoodsMap.get("preferentialPrice").toString().indexOf("%")>=0){
								Double activityPrice=Double.parseDouble(activityGoodsMap.get("preferentialPrice").toString().replaceAll("%", ""));
								Double preferentialPrice=Double.parseDouble(normList.get("preferentialPrice").toString());
								
								normList.put("preferentialPrice",activityPrice*preferentialPrice/100.00);
							}else{
								normList.put("preferentialPrice", Double.parseDouble(activityGoodsMap.get("preferentialPrice").toString()));
							}
							//活动库存
							Integer stock = (Integer)  activityGoodsMap.get("stock");
							//活动商品名称
							goodsMap.put("goodsName", activityGoodsMap.get("goodsName"));
							//秒抢信息
							//获取当前秒抢活动时间段信息
							Map<String,Object> actTimesMap = this.baseSeckillTimesDao.selectBaseSeckillTimesByNow(identifier,seckillTimesId);
							Map<String,Object> seckillInfo=new HashMap<String, Object>();
							seckillInfo.put("seckillStartDate", StringUtil.nullReplace(Long.parseLong(actTimesMap.get("startDate").toString())));
							seckillInfo.put("seckillEndDate", StringUtil.nullReplace(Long.parseLong(actTimesMap.get("endDate").toString())));
							goodsMap.put("seckillInfo",seckillInfo);
							
							//判断库存
							if(stock>0){
								if(goodsBuy-customerGoodsBuy<=0){
									normList.put("stock", 0);
								}else{
									if(stock>goodsBuy-customerGoodsBuy){
										normList.put("stock", goodsBuy-customerGoodsBuy);
									}else{
										normList.put("stock", stock);
									}
								}
							}else{
								normList.put("stock", 0);
							}	
							
						}else if ( identifier != null	&& !identifier.equals("") && (identifier.contains("PT_KJ"))) {
							//获取砍价活动信息
							Map cutMap=new HashMap();
							cutMap.put("identifier", identifier);
							List<BaseCut> CutList=new ArrayList<BaseCut>();
							CutList=baseCutDao.selectBaseCutByIdentifier(cutMap);
							
							
							Integer customerGoodsBuy =0;
							//获取会员在该砍价活动购买商品总数
							customerGoodsBuy = ordersListInterfaceDao.getCustomerCutPriceGoodsBuy(customerId,identifier);
							
							//会员是否参与过活动，已购买过活动商品
							if(customerGoodsBuy==0){
								goodsMap.put("isBuy", "No");
							}else{
								goodsMap.put("isBuy", "YES");
							}
							//活动价格
							normList.put("preferentialPrice", Double.parseDouble(CutList.get(0).getPreferentialPrice().toString()));
							//活动库存
							Integer stock = CutList.get(0).getNumber();
							//活动商品名称
							goodsMap.put("goodsName", CutList.get(0).getGoodsName());
							
							//判断库存
							if(stock>0){
								normList.put("stock", stock);
							}else{
								normList.put("stock", 0);
							}
							
						}else if(identifier != null	&& !identifier.equals("") && (identifier.contains("PT_TG_"))){ //如果为团购活动
							logger.info("identifier_______"+identifier);
							Map<String, Object> dataMap = new HashMap<>();
							dataMap =baseGroupBuyDao.queryInfoByIdentifierGoods(identifier);
							logger.info("dataMap_______"+dataMap);
							Integer alreadyBuy=(Integer) dataMap.get("number")-(Integer) dataMap.get("stock");
							dataMap.put("alreadyBuy", alreadyBuy);
							goodsMap.put("groupBuyInfo", dataMap);
							
							//获取团购活动信息
							Map<String,Object> actMap = this.baseGroupBuyDao.selectBaseGroupBuyIdentifier(identifier);
							//团购活动限购
							Integer goodsBuy = (Integer) actMap.get("maxBuy");
							
							Integer customerGoodsBuy =0;
							//获取会员当天在该活动的当前时间段购买商品总数
							customerGoodsBuy = ordersListInterfaceDao.getCustomerGroupGoodsBuy(customerId,identifier);
							
							//会员是否参与过活动，已购买过活动商品
							if(customerGoodsBuy==0){
								goodsMap.put("isBuy", "No");
							}else{
								goodsMap.put("isBuy", "YES");
							}
							
							//如果活动价有%为按价格打折，否则为活动价格
							if(actMap.get("preferentialPrice").toString().indexOf("%")>=0){
								Double activityPrice=Double.parseDouble(actMap.get("preferentialPrice").toString().replaceAll("%", ""));
								Double preferentialPrice=Double.parseDouble(normList.get("preferentialPrice").toString());
								
								normList.put("preferentialPrice",activityPrice*preferentialPrice/100.00);
							}else{
								normList.put("preferentialPrice", Double.parseDouble(actMap.get("preferentialPrice").toString()));
							}
							//活动库存
							Integer stock = (Integer)  actMap.get("stock");
							
							//判断库存
							if(goodsBuy == 0){  //0表示不限购
								normList.put("stock", stock);
							}else{  //goodsBuy:限购
								if(stock>0){
									if(goodsBuy-customerGoodsBuy<=0){
										normList.put("stock", 0);
									}else{
										if(stock>goodsBuy-customerGoodsBuy){
											normList.put("stock", goodsBuy-customerGoodsBuy);
										}else{
											normList.put("stock", stock);
										}
									}
								}else{
									normList.put("stock", 0);
								}	
							}
							normList.put("number",actMap.get("number"));
						}else {
							//如果为活动
							//获取活动信息
							//限购类型，0 所有商品限购；1 单个商品限购； 2 每日所有商品限购
							Integer limitType = 0;
							//活动限购
							Integer goodsBuy = 0;
							Map actMap=new HashMap<String, Object>();
							if(identifier.contains("CYGHMZS") || identifier.contains("ZXXSZS")){
								actMap = this.baseActivityDao.selectBaseActivityIdentifier(identifier);
								//限购类型，0 所有商品限购；1 单个商品限购； 2 每日所有商品限购
								 limitType = (Integer) actMap.get("limitType");
								//活动限购
								 goodsBuy = (Integer) actMap.get("goodsBuy");
							}else if(identifier.contains("CYBK")){
								actMap = this.baseMoldbabyDao.selectBaseMoldbabyByidentifier(identifier);
								//限购类型，0 所有商品限购；1 单个商品限购； 2 每日所有商品限购
								 limitType = 1;
								//活动限购
								 goodsBuy = 1;
							}
							
							Integer customerGoodsBuy =0;
							if(limitType==1){
								//获取会员购买该活动中该单个商品的购买数量
								customerGoodsBuy = ordersListInterfaceDao.getCustomerGoodsBuyByOrder(customerId,goodsId,identifier,limitType);
							}else if(limitType==0){
								//获取会员在该活动的购买商品总数
								customerGoodsBuy = ordersListInterfaceDao.getCustomerGoodsBuyByOrder(customerId,null,identifier,limitType);
							}else if(limitType==2){
								//获取会员当天在该活动的购买商品总数
								customerGoodsBuy = ordersListInterfaceDao.getCustomerGoodsBuyByOrder(customerId,null,identifier,limitType);
							}
							//会员是否参与过活动，已购买过活动商品
							if(customerGoodsBuy==0){
								goodsMap.put("isBuy", "No");
							}else{
								goodsMap.put("isBuy", "YES");
							}
							
							//获取活动商品信息
							Map<String,Object> activityGoodsMap = goodsListInterfaceDao.queryActivityGoodsInfoByGoodsId(goodsId,identifier);
							//如果活动价有%为按价格打折，否则为活动价格
							if(activityGoodsMap.get("preferentialPrice").toString().indexOf("%")>=0){
								Double activityPrice=Double.parseDouble(activityGoodsMap.get("preferentialPrice").toString().replaceAll("%", ""));
								Double preferentialPrice=Double.parseDouble(normList.get("preferentialPrice").toString());
								
								normList.put("preferentialPrice", activityPrice*preferentialPrice/100.00);
							}else{
								normList.put("preferentialPrice", Double.parseDouble(activityGoodsMap.get("preferentialPrice").toString()));
							}
							//活动库存
							Integer stock = (Integer)  activityGoodsMap.get("stock");
							//活动商品名称
							goodsMap.put("goodsName", activityGoodsMap.get("goodsName"));
							
							//判断库存
							if(stock>0){
								if(goodsBuy-customerGoodsBuy<=0){
									normList.put("stock", 0);
								}else{
									if(stock>goodsBuy-customerGoodsBuy){
										normList.put("stock", goodsBuy-customerGoodsBuy);
									}else{
										normList.put("stock", stock);
									}
								}
							}else{
								normList.put("stock", 0);
							}	
						}
					}
						
					goodsMap.put("photoUrls", photoList);
					goodsMap.put("defaultNorm", normList);

					if (isActivity != null && "1".equals(isActivity)) {
						goodsMap.put("isActivity", isActivity);
					} else {
						goodsMap.put("isActivity", "");
					}

					areaCode = areaCode==null||"".equals(areaCode.trim()) ? "-1" : areaCode;
					logger.info(goodsMap.get("logisticsCostId"));
					if (goodsMap.get("logisticsCostId") != null && !"".equals(goodsMap.get("logisticsCostId"))) {
//						goodsMap.put("logisticsCost", goodsListInterfaceDao.getLogisticsCostByAreaCode(areaCode,
//								goodsId, Integer.valueOf(String.valueOf(goodsMap.get("logisticsCostId")))));
						goodsMap.put("logisticsCost", 8);
					} else {
						goodsMap.put("logisticsCost", 0);
					}
					
					// 活动商品固定运费为广东省8元其它地方12元，ZXXSZS活动不要运费
//					if (isActivity != null && !isActivity.equals("") && isActivity.equals("1") && identifier != null
//							&& !identifier.equals("") ) {
//						if(identifier.contains("CYGHMZS") || identifier.contains("CYBK")){
//							if("44".equals(areaCode.substring(0, 2))|| Integer.parseInt(areaCode)<0){
//								goodsMap.put("logisticsCost", 8);
//							}else{
//								goodsMap.put("logisticsCost", 12);
//							}
//						}else if( identifier.contains("ZXXSZS")){
//							goodsMap.put("logisticsCost", 0);
//						}
//						
//					} else if (Integer.parseInt(areaCode)<0) {
//						goodsMap.put("logisticsCost", 0);
//					}
					
					//判断是否收藏过，1:收藏过,2:没有收藏过
					Map<String, Object> paramMap = new HashMap<String, Object>();
					paramMap.put("goodsId", goodsId);
					paramMap.put("customerId", customerId);
					if(isActivity != null && isActivity.equals("1")){
						//是活动商品
						paramMap.put("identifier", identifier);
					}else{
						paramMap.put("identifier", "0");
					}
					if(seckillTimesId != null){
						//秒抢商品
						paramMap.put("seckillTimesId", seckillTimesId);
					}else{
						paramMap.put("seckillTimesId",0);
					}
					
					GoodsCollection goodsCollection = goodsCollectionDao.getCollection(paramMap);
					if(goodsCollection != null && goodsCollection.getId() != null){
						goodsMap.put("isCollection", 1);
					}else{
						goodsMap.put("isCollection", 2);
					}
					//返还银积分
					Map goodsBrokerageMap = goodsListInterfaceDao.queryGoodsBrokerageById(goodsId);
					if (goodsBrokerageMap != null && !goodsBrokerageMap.isEmpty()) {
						Integer pointsType = Integer.valueOf(goodsBrokerageMap.get("pointsType").toString());// 佣金类型
						goodsMap.put("pointsType", pointsType);  //积分类型 1，自由积分，2，百分比积分
						if (pointsType - 1 == 0) {
							Double points = Double.valueOf(goodsBrokerageMap.get("points").toString());//
							goodsMap.put("points", points);    //自由积分
						} else if (pointsType - 2 == 0) {
							Double pointsPercent = Double.valueOf(goodsBrokerageMap.get("pointsPercent").toString());//
							goodsMap.put("pointsPercent", pointsPercent);   //积分百分比
						}
					}
					
					
					map.put(Constant.STATUS, Constant.STATUS_SUCCESS);
					map.put(Constant.DATA, goodsMap);
					return map;
				} else {
					map.put(Constant.STATUS, Constant.STATUS_ERROR);
					map.put(Constant.ERROR_CODE, Constant.SELECT_ERROR);
					return map;
				}

			} else {
				map.put(Constant.STATUS, Constant.STATUS_ERROR);
				map.put(Constant.ERROR_CODE, Constant.SELECT_ERROR);
				return map;
			}
		} catch (DaoException de) {
			de.printStackTrace();
			logger.error(de);
			throw new ServiceException(de);
		}

	}

	@Override
	public GoodsList queryGoodsListById(Integer id) throws ServiceException {
		try {
			return goodsListInterfaceDao.queryGoodsListById(id);
		} catch (DaoException de) {
			throw new ServiceException(de);
		}
	}

	/**
	 * 
	 * @MethodName searchGoodsByName
	 * @Description 首页商品搜索
	 * 
	 * @author chenpy
	 * @date 2016年1月6日 下午3:25:50
	 * @param
	 * @return Map
	 * @VERSION 1.0.0
	 */
	@Override
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public Map searchGoodsByName(String mallType,String goodsName,String providerId) throws ServiceException {
		Map resultMap = new HashMap();
		if (StringUtils.isEmpty(goodsName)) { // 查询条件为空
			resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
			resultMap.put(Constant.ERROR_CODE, Constant.SYSTEM_REQUEST_PARAM_ERROR);
			return resultMap;
		}

		try {
			logger.info("mallType=========================================="+mallType);
			List<SearchField> fields = searchGoods(mallType,providerId,goodsName, "COMMONS");
			logger.info(JSONUtil.writeValueAsString(fields));
			resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
			resultMap.put(Constant.DATA, fields);
			return resultMap;

		} catch (SolrServerException e) {
			logger.error(e);
			e.printStackTrace();
			throw new ServiceException(e);
		}
	}

	/**
	 * 
	 * @MethodName getGoodsCount
	 * @Description 首页商品统计
	 * 
	 * @author chenpy
	 * @date 2016年1月6日 下午3:25:50
	 * @param
	 * @return Map
	 * @VERSION 1.0.0
	 */
	@SuppressWarnings({ "rawtypes", "unchecked", "serial" })
	public Map getGoodsCount() throws ServiceException {
		Map resultMap = new HashMap();

		try {
			final Integer count = goodsListInterfaceDao.getGoodsCount();

			resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
			resultMap.put(Constant.DATA, new HashMap() {
				{
					put("count", count);
				}
			});
			return resultMap;

		} catch (DaoException e) {
			logger.error(e);
			throw new ServiceException(e);
		}
	}

	/**
	 * 
	 * @MethodName selectGoodsInfoByOrdersIds
	 * @Description 按订单ID集合查询商品信息
	 * 
	 * @author chenpy
	 * @date 2016年1月8日 下午5:20:16
	 * @param
	 * @return List<GoodsList>
	 * @VERSION 1.0.0
	 */
	public List<GoodsList> selectGoodsInfoByOrdersIds(List<Integer> ordersIds) throws ServiceException {
		try {
			return this.goodsListInterfaceDao.selectGoodsInfoByOrdersIds(ordersIds);
		} catch (DaoException e) {
			logger.error(e);
			throw new ServiceException(e);
		}
	}

	/**
	 * 
	 * @MethodName batchUpdateGoodsList
	 * @Description 批量修改商品信息
	 * 
	 * @author chenpy
	 * @date 2016年1月8日 下午5:20:16
	 * @param
	 * @return List<GoodsList>
	 * @VERSION 1.0.0
	 */
	public int batchUpdateGoodsList(List<GoodsList> goodsLists) throws ServiceException {
		try {
			return this.goodsListInterfaceDao.batchUpdateGoodsList(goodsLists);
		} catch (DaoException e) {
			logger.error(e);
			throw new ServiceException(e);
		}
	}

	@Override
	public List<Object> queryGoodsListProviderByIds(List<Integer> ids) throws ServiceException {
		try {
			return goodsListInterfaceDao.queryGoodsListProviderByIds(ids);
		} catch (DaoException de) {
			throw new ServiceException(de);
		}
	}

	@SuppressWarnings("rawtypes")
	public Map queryGoodsBrokerageById(Integer id) throws ServiceException {
		try {
			return goodsListInterfaceDao.queryGoodsBrokerageById(id);
		} catch (DaoException e) {
			throw new ServiceException(e);
		}
	}

	/**
	 * 
	 * @Title: queryGoodsListOfActivity @Description: 查询活动商品列表 @param
	 *         request @return @throws ServiceException @return Map @throws
	 */
	@Override
	public Map queryGoodsListOfActivity(String identifier,String goodsName) throws ServiceException {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> tempMap = new HashMap<String, Object>();
		try {
			
			if (goodsName != null && !goodsName.equals("")) {
				goodsName = URLDecoder.decode(goodsName, "UTF-8");
			}
			
			logger.info("activity Identifier = " + identifier + ", goodsName = " + goodsName);
			List<SearchField> fields = searchGoods(null,null,goodsName, "ACTIVITY", identifier);
			logger.info("fields = " + JSONUtil.writeValueAsString(fields));

			tempMap.put("goodsList", fields);

			map.put(Constant.STATUS, Constant.STATUS_SUCCESS);
			map.put(Constant.DATA, tempMap);

		} catch (SolrServerException | UnsupportedEncodingException de) {
			logger.error(de);
			throw new ServiceException(de);
		}
		return map;
	}

	@Override
	public Map<String, Object> getGoodsInfoByGoodsId(HttpServletRequest request) throws ServiceException {
		try {
			String goodsId = request.getParameter("goodsId");
			String goodsName = request.getParameter("goodsName");
			return goodsListInterfaceDao.getGoodsInfoByGoodsId(Integer.valueOf(goodsId), goodsName);
		} catch (DaoException e) {
			throw new ServiceException(e);
		}
	}

	public BaseActivityDao getBaseActivityDao() {
		return baseActivityDao;
	}

	public void setBaseActivityDao(BaseActivityDao baseActivityDao) {
		this.baseActivityDao = baseActivityDao;
	}

	/**
	 * @Package com.sayimo.school.mall.module.goods.service.impl
	 * @Author 龚益君
	 * @MethodName:queryGoodsListOfMoldbaby
	 * @Description:爆款商品列表
	 * @param request
	 * @return Map<String, Object>
	 * @throws ServiceException
	 * @Date 2016年5月27日,下午3:25:58
	 */
	@Override
	public Map<String, Object> queryGoodsListOfMoldbaby(String identifier,String goodsName) throws ServiceException {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> tempMap = new HashMap<String, Object>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		try {
			logger.info("goodsName = " + goodsName + ", identifier = " + identifier);
			
			List<SearchField> fields = searchGoods(null,null,goodsName, "MOLDBABY", identifier);
			Map<String, Object> moldbabyMap = baseMoldbabyDao.selectBaseMoldbabyByidentifier(identifier);
			tempMap.put("goodsList", fields);
			tempMap.put("startDate", sdf.parse(moldbabyMap.get("startDate").toString()).getTime());
			tempMap.put("endDate", sdf.parse(moldbabyMap.get("endDate").toString()).getTime());
			tempMap.put("moldName", moldbabyMap.get("name"));
			map.put(Constant.STATUS, Constant.STATUS_SUCCESS);
			map.put(Constant.DATA, tempMap);

		} catch (DaoException | SolrServerException | ParseException de) {
			logger.error(de);
			throw new ServiceException(de);
		}
		return map;
	}

	public BaseMoldbabyDao getBaseMoldbabyDao() {
		return baseMoldbabyDao;
	}

	public void setBaseMoldbabyDao(BaseMoldbabyDao baseMoldbabyDao) {
		this.baseMoldbabyDao = baseMoldbabyDao;
	}

	@Override
	public Integer updateStatus(Map<String, Object> paramMap) throws ServiceException {
		try {
			return goodsListInterfaceDao.updateStatus(paramMap);
		} catch (DaoException e) {
			throw new ServiceException(e);
		}
	}

	/**
	 * 
	 * @Title: getTshGoodStockNum
	 * @Author: 田超
	 * @Date:日期：2016年6月28日 时间：下午1:50:00
	 * @Description: 调用特奢汇商品库存接口,获得实时商品库存
	 * @return
	 * @return String
	 * @Version 1.0.0
	 */
	public String getTshGoodStockNum(String skuCode) {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		Map<String, Object> dataMap = new HashMap<String, Object>();
		Map<String, Object>[] map = new Map[1];
		Map<String, Object> stockMap = new HashMap<String, Object>();
		stockMap.put("skuCode", skuCode);
		map[0] = stockMap;
		dataMap.put("stockList", map);
		paramMap.put("action", "getProductStock");
		paramMap.put("app_key", app_key);
		paramMap.put("dist_code", dist_code);
		paramMap.put("typeId", typeId);
		paramMap.put("data", dataMap);

		String sign = SignUtil.getSign(paramMap, token);

		paramMap.put("sign", sign);

		logger.info("paramMap =" + JSONUtil.writeValueAsString(paramMap));
		String json = HttpUtils.postMethod(url, paramMap);
		logger.info("json " + json);
		return json;
	}
	
	/**
	 * 
	* @Title: checkGoodStatus 
	* @Author: 田超
	* @Date:日期：2016年6月28日  时间：下午2:47:38
	* @Description: 调用特奢汇接口,获得商品上下架装太
	* @return
	* @return String
	* @Version 1.0.0
	 */
	public String checkGoodStatus(String skuCode){
		Map<String, Object> paramMap = new HashMap<String, Object>();
    	Map<String, Object> dataMap = new HashMap<String, Object>();
    	Map<String, Object>[] map = new Map[1];
    	Map<String, Object> stockMap = new HashMap<String, Object>();
    	stockMap.put("skuCode", skuCode);
    	map[0] = stockMap;
		dataMap.put("productList",map);
		paramMap.put("action", "getProductDetail");
    	paramMap.put("app_key", app_key);
    	paramMap.put("dist_code", dist_code);
    	paramMap.put("typeId", typeId);
    	paramMap.put("data", dataMap);
    	
    	String sign = SignUtil.getSign(paramMap,token);
    	
    	paramMap.put("sign", sign);
    	logger.info("paramMap ="+JSONUtil.writeValueAsString(paramMap));
    	String json = HttpUtils.postMethod(url, paramMap);
    	logger.info("json " + json);
    	return json;
	}
	
	/**
	 * @package com.sayimo.school.mall.module.goods.service.impl
	 * @author chenpy
	 * @Title:
	 * @Description:
	 * @param
	 * @throws @return
	 *             List<SearchField>
	 * @date 2016年8月11日
	 */
	private List<SearchField> searchGoods(String mallType,String providerId,String goodsName, String type, String... identifier)
			throws SolrServerException {
		logger.info("goodsName = " + goodsName);
		if (StringUtils.isNotEmpty(goodsName)) {
			try {
				goodsName = URLDecoder.decode(URLDecoder.decode(goodsName, "UTF-8"), "UTF-8");
				logger.info("goodsName = " + goodsName);
			} catch (UnsupportedEncodingException e) {
				logger.error(e);
			}
		}
		SolrServer solrServer = SearchUtil.getSolrServer();
		SolrQuery solrQuery = new SolrQuery();

		Pattern pattern = Pattern.compile(Constant.REGEX_NUM_LATTER);
		Matcher matcher = null;
		StringBuilder builder = new StringBuilder();
		if (StringUtils.isNotEmpty(goodsName)) {
			matcher = pattern.matcher(goodsName);
			if (matcher.find()) {
				builder.append(matcher.group().toLowerCase());
			}
			logger.info("build = " + builder.toString());
		}
		solrQuery.set("q", "pinyin:" + (StringUtils.isEmpty(builder.toString()) ? "*" : builder.toString()))
				.set("defType", "edismax").set("mm", 20);
		solrQuery.setStart(0);
		solrQuery.setRows(100000);
		if (identifier != null && identifier.length > 0) {
			solrQuery.addFilterQuery("identifier:" + identifier[0]);
		}
		solrQuery.addFilterQuery("type:" + type);
		//商城类型  所属商城 1金商城 2银商城 3全返商城 4商企商品
		solrQuery.addFilterQuery("mallType:" + mallType);
		//供应商id
		if(providerId!=null&&!"".equals(providerId)){
			solrQuery.addFilterQuery("providerId:" + providerId);
		}
		
		solrQuery.setFields("normsValueId", "name", "goodsId", "photoUrl", "sellNum", "originalPrice",
				"preferentialPrice", "story");
		if (StringUtils.isNotEmpty(goodsName)) {
			while (matcher.find()) {
				builder = new StringBuilder("pinyin:");
				builder.append(matcher.group());
				logger.info("fq = " + builder.toString());
				solrQuery.addFilterQuery(builder.toString());
			}
		}

		QueryResponse queryResponse = solrServer.query(solrQuery);
		logger.info("response time = " + queryResponse.getQTime());

		return queryResponse.getBeans(SearchField.class);
	}

	/**
	 * @package com.sayimo.school.mall.module.goods.service
	 * @author chenpy
	 * @Title:
	 * @Description: 前端商品搜索时提示建议
	 * @param goodsName 商品名称
	 * @param type 商品类型：
	 * 				1、普通商品
	 * 				2、活动商品
	 * 				3、爆款商品
	 * @param classId 商品分类ID
	 * @throws @return
	 *             Map<String,Object>
	 * @date 2016年8月15日
	 */
	public Map<String, Object> suggestGoodsSearch(String mallType,String goodsName,Integer type,String classId) throws ServiceException {
		Map<String, Object> resultMap = new HashMap<>();
		type = (type==null ? 1: type);
		
		logger.info("classId = " + classId);
		
		logger.info("goodsName = " + goodsName);
		
		logger.info("mallType = " + mallType);
		
		try {
			goodsName = URLDecoder.decode(URLDecoder.decode(goodsName, "UTF-8"), "UTF-8");
			resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
			List<String> dataList = new ArrayList<>();
			logger.info("goodsName = " + goodsName);
			SolrServer solrServer = SearchUtil.getSolrServer();
			SolrQuery solrQuery = new SolrQuery();
			solrQuery.setRequestHandler("/spell").set("q", goodsName).set("defType", "edismax")
					.set("spellcheck.count", 4).set("mm", 6);
			
			solrQuery.addFilterQuery("providerType:1"); // 普通商品（非学生店铺商品）
			if (type == 1) {
				solrQuery.addFilterQuery("identifier:COMMON_GOODS");
			} else if (type == 2) {
				solrQuery.addFilterQuery("type:ACTIVITY");
			} else {
				solrQuery.addFilterQuery("type:MOLDBABY");
			}
			
			if (StringUtils.isNotEmpty(classId)) {
				solrQuery.addFilterQuery("classId:" + classId);
			}

			//商城类型  所属商城 1金商城 2银商城 3全返商城 4商企商品
			solrQuery.addFilterQuery("mallType:" + mallType);
			
			
			logger.info("solrquery = " + solrQuery);
			QueryResponse queryResponse = solrServer.query(solrQuery);
			logger.info(JSONUtil.writeValueAsString(queryResponse));
			SpellCheckResponse checkResponse = queryResponse.getSpellCheckResponse();
			if (checkResponse != null && !checkResponse.isCorrectlySpelled()) {
				List<Suggestion> suggestions = checkResponse.getSuggestions();
				if (CollectionUtils.isNotEmpty(suggestions)) {
					Suggestion suggestion = checkResponse.getSuggestions().get(0);
					for (String string : suggestion.getAlternatives()) {
						dataList.add(string);
					}
				}
			}

			List<SearchField> fields = queryResponse.getBeans(SearchField.class);
			if (CollectionUtils.isNotEmpty(fields)) {
				for (SearchField searchField : fields) {
					dataList.add(searchField.getGoodsName());
				}
			}

			resultMap.put(Constant.DATA, dataList);
			return resultMap;
		} catch (SolrServerException | UnsupportedEncodingException e) {
			logger.error(e);
			throw new ServiceException(e);
		}
	}
	/** 
	* @Title: unionShopList 
	* @Description: 联盟商家列表
	* @param request
	* @return
	* @return Map<String,Object>
	* @throws 
	*/
	@Override
	public Map<String, Object> unionShopList(Integer unionshopClassId,String longitude,String latitude,Integer pageNow,Integer pageSize,String providerName) throws ServiceException {
		Map<String,Object> resultMap=new HashMap<String,Object>();
		Map<String,Object> paramMap=new HashMap<String,Object>();
		try {
			paramMap.put("unionshopClassId", unionshopClassId);
			paramMap.put("longitude", longitude);
			paramMap.put("latitude", latitude);
			if(pageNow != null && pageNow == 0){
				paramMap.put("pageNow", 0);
			}else if(pageNow != null && pageNow > 0){
				paramMap.put("pageNow", (pageNow-1)*pageSize);
			}
			if(pageSize != null){
				paramMap.put("pageSize", pageSize);
			}
			logger.info("providerName = " + providerName);
			if (StringUtils.isNotEmpty(providerName)) {
				try {
					providerName = URLDecoder.decode(URLDecoder.decode(providerName, "UTF-8"), "UTF-8");
					paramMap.put("providerName", providerName);
					logger.info("providerName = " + providerName);
				} catch (UnsupportedEncodingException e) {
					logger.error(e);
				}
			}
			
			
			List list =  goodsListInterfaceDao.unionShopList(paramMap);
			if(list!=null&&list.size()>0){
				
				Map<String,Object> tempMap=new HashMap<String, Object>();
				tempMap.put("unionShopList", list);
				
				resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
				resultMap.put(Constant.DATA, tempMap);
			}else{
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.ERROR_CODE,Constant.SELECT_ERROR);
			}
			return resultMap;
		} catch (DaoException e) {
			logger.error(e);
			throw new ServiceException(e);
		}
	}
	/**
	 * @Package com.sayimo.maker.mall.goods.service.impl
	 * @Author TANXIN
	 * @MethodName:unionShopById
	 * @Description:联盟商家详情
	 * @param providerId
	 * @return
	 * @throws ServiceException
	 * @Date 2017年2月18日,下午2:07:33
	 */
	@Override
	public Map<String, Object> unionShopById(Integer providerId) throws ServiceException {
		Map<String,Object> resultMap=new HashMap<String,Object>();
		Map<String,Object> paramMap=new HashMap<String,Object>();
		try {
			paramMap.put("providerId", providerId);
			Map map =  goodsListInterfaceDao.unionShopById(paramMap);
			String rotationPhotoIds=(String)map.get("rotationPhotoIds");
			if(map!=null){
				Map<String,Object> tempMap=new HashMap<String, Object>();
				tempMap.put("unionShop", map);
				if(rotationPhotoIds!=null&&!"".equals(rotationPhotoIds)){
					List<BasePhoto> basePhotoList=basePhotoDao.selectAllById(rotationPhotoIds);
					tempMap.put("basePhotoList", basePhotoList);
				}
				
				resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
				resultMap.put(Constant.DATA, tempMap);
			}else{
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.ERROR_CODE,Constant.SELECT_ERROR);
			}
			return resultMap;
		} catch (DaoException e) {
			logger.error(e);
			throw new ServiceException(e);
		}
	}
}
